﻿using Apache.NMS;
using Apache.NMS.ActiveMQ;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Recive
{
    public partial class Form1 : Form
    {

        private IConnectionFactory factory;
        public Form1()
        {
            InitializeComponent();
            InitProducer();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public void InitProducer()
        {
            //初始化工厂，这里默认的URL是不需要修改的
            //Create the Connection factory  
            factory = new ConnectionFactory("tcp://localhost:61616/");

            //Create the connection  
            IConnection connection = factory.CreateConnection();

            connection.ClientId = "testing listener1";
            connection.Start();

            //Create the Session  
            ISession session = connection.CreateSession();
            //Create the Consumer  
            IMessageConsumer consumer = session.CreateDurableConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("testing"), "testing listener1", null, false);
            consumer.Listener += new MessageListener(consumer_Listener);

            //connection.Stop();
            //connection.Close();

        }

        public void consumer_Listener(IMessage message)
        {
            if (this.IsHandleCreated)
            {
                ITextMessage msg = (ITextMessage)message;
                //异步调用下，否则无法回归主线程
                lb1.Invoke(new DelegateRevMessage(RevMessage), msg);
            }
        }


        public delegate void DelegateRevMessage(ITextMessage message);

        public void RevMessage(ITextMessage message)
        {
            lb1.Text += string.Format(@"接收到:{0}{1}", message.Text, Environment.NewLine);
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }
    }
}
